﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Knlght.Web.Infrastructure.Filters
{
    /// <summary>
    /// ZB 验证过滤器
    /// </summary>
    public class EJAuthorizeAttribute : AuthorizeAttribute
    {
        public EJAuthorizeAttribute()
        {
            IsStartWith = true;
        }
        /// <summary>
        /// 当前验证过滤器默认跳转的登录url
        /// </summary>
        public string LoginUrl { get; set; }
        /// <summary>
        /// 是否开头匹配，否的话为等于
        /// </summary>
        public bool IsStartWith { get; set; }
        /// <summary>
        /// 登陆验证的结果：1、验证成功（包括店铺还有会员），2、验证失败，没登陆（包括店铺还有会员），3、店铺没权限（登陆账号仅有会员功能）
        /// </summary>
        public int Result { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                this.Result = 2;
                return false;
            }

            if (!string.IsNullOrEmpty(Roles))
            {
                var formIdentity = user.Identity as System.Web.Security.FormsIdentity;
                if (formIdentity != null)
                {
                    if (IsStartWith)
                    {
                        if (formIdentity.Ticket.UserData.ToLower().StartsWith(Roles.ToLower()))
                        {
                            this.Result = 1;
                            return true;
                        }
                        else
                        {
                            this.Result = 2;
                            return false;
                        }
                    }
                    else
                    {
                        if (Roles.ToLower() == formIdentity.Ticket.UserData.ToLower())
                        {
                            this.Result = 1;
                            return true;
                        }
                        else
                        {
                            if (formIdentity.Ticket.UserData.ToLower() == "member")
                            {
                                this.Result = 3;
                                return false;
                            }
                            else
                            {
                                this.Result = 2;
                                return false;
                            }
                        }
                    }
                }
            }

            this.Result = 1;
            return true;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (filterContext.Result is HttpUnauthorizedResult && !string.IsNullOrEmpty(LoginUrl))
            {
                if (this.Result == 3)
                {
                    filterContext.Result = new RedirectResult("/Account/NoPermissions");
                }
                else
                {
                    var returnUrl = filterContext.HttpContext.Request.Url.PathAndQuery;
                    returnUrl = filterContext.HttpContext.Server.UrlEncode(returnUrl);
                    var url = string.IsNullOrEmpty(returnUrl) ? LoginUrl : string.Format("{0}?ReturnUrl={1}", LoginUrl, returnUrl);
                    filterContext.Result = new RedirectResult(url);
                }
            }
        }
    }
}
